/**
 * 获取随机数UUID
 */
export const createUUID = (len = 12, radix?: number): string => {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  const uuid: string[] = []
  let i
  radix = radix || chars.length

  if (len) {
    for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)]
  } else {
    let r
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16)
        uuid[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r]
      }
    }
  }
  return uuid.join('')
}

/**
 * 获取URL参数
 */
export const getUrlParam = (sUrl: string, sKey: string): any => {
  const result: any = {}
  sUrl.replace(/(\w+)=(\w+)(?=[&|#])/g,  function(ele:any, key:string, val: any): any {
    if (!result[key]) {
      result[key] = val
    } else {
      const temp = result[key]
      result[key] = [].concat(temp, val)
    }
  })
  if (!sKey) {
    return result
  } else {
    return result[sKey] || ''
  }
}

/**
 * jsonp数据请求
 */
export const jsonp = (url:string, callback:any): void => {
  const oscript:any = document.createElement('script')
  if (oscript.readyState) {
    // ie8及以下版本
    oscript.onreadystatechange = function () {
      if (oscript.readyState === 'complete' || oscript.readyState === 'loaded') {
        callback()
      }
    }
  } else {
    oscript.onload = function () {
      callback()
    }
  }
  oscript.src = url
  document.body.appendChild(oscript)
}

/**
 * 文件操作相关，如果是图片直接打开，是其他文件点击直接下载
 * @param url
 * @param name
 */
export const downloadByUrl = (url:string, name:string): void => {
  // 创建a标签
  const a = document.createElement('a')
  // 隐藏标签
  a.style.display = 'none'
  // 设置文件路径
  a.href = url
  a.target = '_blank'
  a.download = name
  // 将创建的标签插入dom
  document.body.appendChild(a)
  // 点击标签，执行下载
  a.click()
  // 将标签从dom移除
  document.body.removeChild(a)
}
